package cn.alm.spring03tx.dao;

import cn.alm.spring03tx.entity.Account;
import jakarta.annotation.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class AccountDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public Account getAccountById(Integer id) {
        String url = "select * from tb_account where id = ?";
        Account account = jdbcTemplate.queryForObject(url, new BeanPropertyRowMapper<>(Account.class), id);
        return account;
    }

    public void updateAccountById(Integer id, BigDecimal cost) {
        // 先查询是否有足够的余额
        Account accountById = getAccountById(id);
        BigDecimal balance = accountById.getBalance();
        if (balance.compareTo(cost) < 0) {
            System.out.println("余额不足");
            throw new RuntimeException("余额不足");
        }
        String url = "update tb_account set balance = ? where id = ?";
        int update = jdbcTemplate.update(url, balance.subtract(cost), id);
        if (update == 0) {
            System.out.println("更新失败");
        } else {
            System.out.println("更新成功");
        }
    }
}
